package com.gg.web;

import com.gg.pojo.User;
import com.gg.service.UserService;
import com.gg.service.impl.UserServiceImpl;
import com.gg.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    //操作数据库
    private UserService userService = new UserServiceImpl();

    //验证用户名是否已被用
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数 username
        String username = req.getParameter("username");
        //调用userService.existsUsername
        boolean existUsername = userService.existUsername(username);
        //把返回结果封装成Map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existUsername",existUsername);
        //转换成JSON字符串响应回客户端
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**
     * 处理注销功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session中的用户登录信息（或者销毁Session）
        req.getSession().invalidate();
        //2.重定向到首页（或者登录页面）
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 处理登录请求的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调用userService.login()处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        if(loginUser==null){
            //登录失败，把错误信息和回显的表单项信息，保存到Request域中
            req.setAttribute("msg","用户名或密码错误！");
            req.setAttribute("username",username);
            // 跳回登录页面
            System.out.println("用户名或密码错误");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else {
            System.out.println("登录成功！");
            //登录成功，将用户信息保存到Session中
            req.getSession().setAttribute("user",loginUser);
            //跳到登录成功页面
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }
    }

    /**
     * 处理注册请求的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中验证码，防止复用
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //1.获取请求参数,通过标签name属性
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

        //2.验证验证码
        if(token != null && token.equalsIgnoreCase(code) ){
            //正确
            //3.检验用户名是否可用
            if(userService.existUsername(username)){
                //不可用，将用户名已存在提示信息存入Request域中回显
                req.setAttribute("msg","用户名已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                // 跳回注册页面
                System.out.println("用户名["+username+"]已存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                //可用，调用UserService保存到数据库
                userService.registUser(new User(null,username,password,email));
                //跳到注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else {
            //不正确，将错误信息和回显标签字段保存到Request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);

            // 跳回注册页面(请求重定向)
            System.out.println("验证码["+code+"]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

    /*@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        *//*if("login".equals(action)){
            login(req,resp);

        }else if ("regist".equals(action)){
            regist(req,resp);
        }*//*

        //代码进一步优化，避免以后User模块添加新功能，如：修改密码，绑定手机号等业务功能时
        //还需要改动doPost追加大量else if，利用反射可以让开发者只专注于开发新功能方法代码
        try {
            //获取action业务 鉴别字符串，获取相应业务 方法反射对象
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //反射调用目标业务方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
